from flask import Blueprint,request,redirect,make_response,Response,render_template
from application.models.model import *
from swaager_init import siwa,BaseModel
from db_init import db
from tools.data_tools import orm2dict, ret_route, limit_framt
from cache import my_cache
from tools.ali_pay import alipay
import time,requests
from tools.get_qiniu_token import get_qiniu_token
from sqlalchemy import text
from flask_login import current_user,login_required

back = siwa.blueprint("back", __name__)

@back.route('/tags',methods=['get'])
def get_all_tags():
    tag = Tags.query.all()
    tag_list = [orm2dict(i) for i in tag]
    return ret_route(200,tag_list)

# 根据标签查课程
@back.route('/get_course',methods=['get'])
def get_course_by_tag():
    data = request.args.get('data')
    tags = Tags.query.filter(Tags.name == data).first()
    course = tags.courses
    course_list = []
    for i in course:
        course_list.append(i.id)
    course_data_list = db.session.query(Course).filter(Course.id.in_(course_list)).all()
    course_ = []
    for i in course_data_list:
        course_.append(orm2dict(i))
    return ret_route(200,course_)

# 添加课程
@back.route('/add_course',methods=['post'])
def add_course():
    course = request.json
    db.session.add(Course(**course))
    db.session.commit()
    return ret_route(200)

# 给课程添加章节
@back.route('/add_chapter',methods=['post'])
def add_chapter():
    chapter = request.json
    db.session.add(Chapter(**chapter))
    db.session.commit()
    return ret_route(200)

# 支付宝支付
@back.route('/<int:order_id>/payment',methods=['get'])
def order_pay(order_id):
    ali_ret = alipay.client_api(
        "alipay.trade.page.pay",
    biz_content = {
    "out_trade_no": order_id,
    "total_amount": 1.1,
    "subject": "中文也没问题",
    "product_code": "FAST_INSTANT_TRADE_PAY",
    },
    return_url=f"http://127.0.0.1:9527/order/{order_id}?type=ali",  # this is optional
    )
    my_cache.lpush('ali_order', str(order_id) + '/' + ali_ret)
    return str(time.time())

# 获取七牛云的token
@back.route('/qi_token',methods=['get'])
def get_token():
    return ret_route(200,get_qiniu_token())

# 修改用户的信息
@back.route('/update_img/<int:user_id>',methods=['put'])
def put_user_info(user_id):
    user_info = request.json
    User.query.get(user_id).update(user_info)
    db.session.commit()
    return ret_route(200)

# 获取新闻的数据
@back.route('/check/news',methods=['get'])
@login_required
def check_get_something():
    # 默认以id排序
    order = request.args.get('order','id')
    news_type = request.args.get('news_type')
    limit, offset = limit_framt(dict(request.args))
    news = News.query
    if news_type:
        news = news.filter_by(news_type=news_type)
    data = news.order_by(text(f'-top,{order}')).limit(limit).offset(offset * limit).all()
    ret_data = orm2dict(data)
    # 一一对应
    for orm,dic in zip(data,ret_data):
        dic['user'] = orm2dict(orm.user,filter=['password'])
        dic['c'] = orm2dict(orm.course)
    return ret_route(200,data=ret_data)

# 获取单个的详情
@back.route('/<int:news_id>/news_info',methods=['get'])
def check_news_info(news_id):
    news_data = News.query.get(news_id)
    # ret_data = orm2dict(news_data)
    # ret_data['user_name'] = news_data.user.nikename
    # ret_data['user_url'] = news_data.user.url
    # ret_data['course_name'] = news_data.course.name
    return render_template('new_tag.html',new_html_tag = orm2dict(news_data))

# 编辑
@back.route('/news_info',methods=['post'])
@login_required
def update_news_info():
    news_data = dict(request.json)
    news_data['c_time'] = int(time.time())
    # news_data['user_id'] = current_user.id
    news_data['user_id'] = 1
    db.session.add(News(**news_data))
    db.session.commit()
    return ret_route(200)

@back.route('/edit',methods=['get'])
def add_edit():
    return render_template('md_text.html')

@back.route('/types',methods=['get'])
def get_types():
    return ret_route(data=list(News.types_column))

# 订单过期时间数据
@back.route('/over_time',methods=['delete'])
def delete_tcourse():
    #前端获取数据
    u_id = request.args.get('u_id')
    #先取出属于哪一个用户
    order = Order.query.filter(Order.user == u_id).first()
    # 直接判断订单的时间是否过期
    if order:
        now_time = time.time().__trunc__()
        #直接判断订单的时间是否大于当前的时间，如果大就删除，如果没有，放任不管
        order_data = Order.query.filter(Order.end_t <= now_time).all()
        if order_data:
            Order.query.filter(Order.user == u_id).delete()
            db.session.commit()
    return ret_route(200)

# 定时上线训练营、视频
@back.route('/add_tocourse',methods=['post'])
def add_tocourse_by_time():
    data = request.json
    time_ = data['time']
    now_time = time.time().__trunc__()
    if now_time <= time_:
        db.session.add(Tcourse(**data))
        db.session.commit()
    return ret_route(200)

# 监控
@back.route('/', methods=['POST'])
def index():
    data = request.json
    url = "https://oapi.dingtalk.com/robot/send?access_token=c42ae971590b607310e128b490a8aef9119c33929f48d944bf620ca9cf8c2271"
    ret = requests.post(url, json={
        "msgtype": "markdown",
        "markdown": {
            "title": "监控",
            "text": f"""#### 监控通知 \n
> cpu {data['cpu_info']}\n
> 内存总量 {data['total_memory']}G\n
> 已用内存 {int(data['used_memory'])}\n
@17611406668"""
        },
        "at": {
            "atMobiles": [
                "17611406668"
            ],
            "atUserIds": [
                "vqt_2ayf8q6bb"
            ],
            "isAtAll": False
        }
    })
    print(ret.json())
    return "ok"

